/**
 * 
 */
package ua.ws.feedsreader.listeners;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import ua.ws.feedsreader.loaders.SchedulerManager;

/**
 * @author ricardo
 *
 */
public class FeedsLoaderListener implements ServletContextListener {
	
	
	private ScheduledExecutorService executor;
    private SchedulerManager service;

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		
		executor.shutdown();
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		service = new SchedulerManager();
        // setup single thread to run background service every 5 minutes
        executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate((Runnable) service, 0, 15, TimeUnit.MINUTES);
        // make the background service available to the servlet context
        sce.getServletContext().setAttribute("service", service);
	}

}
